package com.fyl.leetcode.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * @author:fyl
 * @date 2021/5/23 16:34
 * @Modified By:
 * @Modified Date:
 * @Description:
 * 给定一个不含重复数字的数组 nums ，返回其所有可能的全排列 。你可以 按任意顺序 返回答案。
 * 输入：nums = [1,2,3]
 * 输出：[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 */
public class Permute {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> resList = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        boolean[] visited = new boolean[nums.length];
        def(nums, visited, resList, list);
        return resList;
    }

    private void def(int[] nums, boolean[] visited, List<List<Integer>> resList, List<Integer> list) {
        if (list.size() == nums.length) {
            resList.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (visited[i]) {
                continue;
            }
            visited[i] = true;
            list.add(nums[i]);
            def(nums, visited, resList, list);
            //遍历过后将list最后一个数字删除，便于下一次循环替换新的数字,状态重置
            list.remove(list.size()-1);
            visited[i] = false;
        }
    }
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        Permute solution = new Permute();
        List<List<Integer>> lists = solution.permute(nums);
        System.out.println(lists);
    }

}
